package com.xixi.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import com.xixi.demo.config.CaptchaProperties;
import com.xixi.demo.model.Result;
import com.xixi.demo.model.UserInfo;
import com.xixi.demo.service.UserService;
import com.xixi.demo.utils.JWTUtils;
import com.xixi.demo.utils.SecurityUtils;
import io.jsonwebtoken.lang.Assert;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CaptchaProperties captchaProperties;


    /**
     * 用户登录
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public Result<UserInfo> userLogin(String userName, String password){
        log.info("userLogin接收参数:{},{}", userName, password);
//        Assert.hasLength(userName,"用户名不能为空");
//        Assert.hasLength(password,"密码不能为空");
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.noUserNameOrPassword();
        }

        UserInfo userInfo = userService.selectUserInfoByName(userName);
        if(userInfo == null){
            return Result.noFindUserName();
        }
        if(!SecurityUtils.verity(password, userInfo.getPassword())){
            return Result.errorPassword();
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", userInfo.getId());
        claims.put("name", userInfo.getUserName());
        String jwt = JWTUtils.genJwt(claims);
        return Result.success(jwt);

    }

    /**
     * 用户注册
     * @param userName
     * @param password
     * @param githubUrl
     * @return
     */
    @RequestMapping("/registry")
    public Result<Boolean> registry(HttpSession session, String userName, String password, String githubUrl, String captcha) {
        log.info("registry接收参数:{},{},{},{}", userName, password, githubUrl, captcha);
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)
                || !StringUtils.hasLength(githubUrl)) {
            return Result.noUserNameOrPasswordOrGithubUrl();
        }
        if(!StringUtils.hasLength(captcha)){
            return Result.noCaptcha();
        }
        Result<Boolean> verify = userService.checkHomeCaptcha(captcha, session);

        if (verify.getData()) {
            password = SecurityUtils.encrypt(password);
            Integer result = userService.registry(userName, password, githubUrl);
            if (result == 1) {
                return Result.success(true);
            } else {
                return Result.fail("注册失败");
            }
        }
        return verify;
    }

    /**
     * 生成验证码
     */
    @SneakyThrows
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        response.setContentType("image/jpeg");
        //禁止使用缓存
        response.setHeader("Pragma", "No-cache");
        //图形验证码写出，可以写出到文件，也可以写出到流
        lineCaptcha.write(response.getOutputStream());
        //将生成的验证码存储到session中, 方便后续进行验证
        session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());
        //将当前时间存储到session中, 方便后续进行验证验证码是否过期
        session.setAttribute(captchaProperties.getSession().getDate(), new Date());
        //输出code
        Console.log(lineCaptcha.getCode());
        response.getOutputStream().close();
    }


    /**
     * 主页面展示 登录用户的信息
     * @param request
     * @return
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        String jwt = request.getHeader("user_token_header");
        Integer userId = JWTUtils.getUserIdFromToken(jwt);
        if(userId != null){
            return userService.selectUserInfoById(userId);
        }
        return null;
    }


    /**
     * 详情页面展示 作者信息
     * @param blogId
     * @return
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        if(blogId == null || blogId < 0){
            return null;
        }
        return userService.getAuthorInfo(blogId);
    }
}
